<?php

namespace SC\Sitemap;

use Illuminate\Support\Facades\Cache;
use Closure;

class Sitemap
{
    protected $generators = [];
    protected $cacheKey = 'sitemap:cache';
    protected $cacheSeconds = 3600*24;

    public function cacheHours($hours)
    {
        $this->cacheSeconds = $hours * 3600;
        return $this;
    }

    public function cacheKey()
    {
        return $this->cacheKey;
    }

    public function register(Closure $closure)
    {
        $this->generators[] = $closure;
    }

    public function render()
    {
        if (\is_file(app_path('sitemap.php'))) {
            require(app_path('sitemap.php'));
        }
        return $this->generate();
    }

    public function generate()
    {
        if (app()->environment('production')) {
            if ($sitemap = Cache::get($this->cacheKey)) {
                return $sitemap;
            }
        }

        $collector = new Collector;
        foreach($this->generators as $generator) {
            \call_user_func($generator, $collector);
        }

        $items = $collector->items();
        $sitemap = view('sitemap::sitemap', ['items' => $items])->render();
        if ($items) {
            Cache::put($this->cacheKey, $sitemap, $this->cacheSeconds);
            return $sitemap;
        }
        return $sitemap;
    }
}